/*
 * httpmsg.cpp
 *
 *  Created on: Apr 14, 2009
 *      Author: kuncai
 */
#include "httpmsg.h"
#include <string>
using namespace std;
HttpMsg::HttpMsg(){
	sMsg = "";
}
HttpMsg::HttpMsg(string msg){
	sMsg = msg;
}
HttpMsg::~HttpMsg(){}
int HttpMsg::SetHeader(string name, string value){
	pair<map<string, string>::iterator, bool> Insert_Pair;
	Insert_Pair = mHeaderList.insert(pair<string, string>(name, value));
	if(Insert_Pair.second == true)
		return true;
	else
		return false;
}
string HttpMsg::GetHeader(string name){
	string value="";
	map<string,string>::iterator iter;
	iter = mHeaderList.find(name);
	if(iter != mHeaderList.end()){
		value = iter->second;
	}
	int i=0;
	for(i=0; i<value.length(); i++){
		if(value.at(i) != ' ')break;
	}
	if(i != 0 )
		Log::Debug("have %d space\n",i);
	return	value.substr(i);
}
int HttpMsg::SetContent(Buffer* content){
	sContent.Clear();
	sContent.Append(content->GetByteBuffer(),content->GetLimit());
	return 1;
}
Buffer* HttpMsg::GetContent(){
	return &sContent;
}
string HttpMsg::strspilt(string* str, string needle){
	int loc = 0;
	loc = (*str).find(needle,0);
	string res = "";
	if(loc != string::npos){
		res =(*str).substr(0,loc);
		(*str) = (*str).substr(loc + needle.length());
	}else{
		res = *str;		
	}
	return res;
}

int HttpMsg::HttpSpilt_q(string qMsg, map<string,float>* qList){
	string item = "";
	int mapLen = 0;
	while((item = strspilt(&qMsg, ",")) != ""){
		Log::Debug("item:%s\n",item.c_str());
		Log::Debug("qMsg:%s\n",qMsg.c_str());
		if(item == qMsg)qMsg = "";
		string sKey,sValue;
		float fValue = 1;	
		sKey = "";
		sValue = "";
		sKey = strspilt(&item, ";");
		if(sKey == ""){
			continue;
		}
		Log::Debug("sKey:%s\n",sKey.c_str());
		if(item != ""  && strspilt(&item, "q=") != item){
			sValue = item;
			fValue = atof(sValue.c_str());
		}
		Log::Debug("sValue:%f\n",fValue);
		//delete space
		int i=0;
		for(i=0; i<sKey.length(); i++){
			if(sKey.at(i) != ' ')break;
		}
		sKey = sKey.substr(i);
		//end delete space
		pair<map<string, float>::iterator, bool> Insert_Pair;
		Insert_Pair = qList->insert(pair<string, float>(sKey, fValue));
		if(Insert_Pair.second == false){
			return -1;
		}
		mapLen++;
	}
	return mapLen;
}
